import React, { useState, useEffect } from 'react'
import {
  Modal,
  Tree,
  Table,
  Card,
  Row,
  Col,
  Input,
  Select,
  Space,
  Typography,
  Tag,
  Tooltip,
  Spin,
  Empty,
  Button,
  message,
} from 'antd'
import type { TreeDataNode } from 'antd/es/tree'
import type { ColumnsType } from 'antd/es/table'
import {
  DatabaseOutlined,
  TableOutlined,
  ColumnHeightOutlined,
  SearchOutlined,
  ReloadOutlined,
  CopyOutlined,
  KeyOutlined,
  InfoCircleOutlined,
} from '@ant-design/icons'
import type { Connection, DatabaseSchema } from '@/types/connection'
import { getDatabaseSchema, getDatabases, getTables, getTableSchema } from '@/services/connectionAPI'
import { copyToClipboard } from '@/utils'

const { Search } = Input
const { Option } = Select
const { Text, Title } = Typography

interface DatabaseSchemaProps {
  visible: boolean
  connection: Connection | null
  onClose: () => void
}

interface TableColumn {
  name: string
  type: string
  nullable: boolean
  default?: string
  comment?: string
  isPrimaryKey?: boolean
  isIndex?: boolean
}

interface SchemaTreeNode extends TreeDataNode {
  type: 'database' | 'table' | 'column'
  database?: string
  table?: string
  column?: TableColumn
}

const DatabaseSchema: React.FC<DatabaseSchemaProps> = ({
  visible,
  connection,
  onClose,
}) => {
  const [loading, setLoading] = useState(false)
  const [databases, setDatabases] = useState<string[]>([])
  const [selectedDatabase, setSelectedDatabase] = useState<string>()
  const [treeData, setTreeData] = useState<SchemaTreeNode[]>([])
  const [selectedTable, setSelectedTable] = useState<string>()
  const [tableColumns, setTableColumns] = useState<TableColumn[]>([])
  const [searchKeyword, setSearchKeyword] = useState('')
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([])

  // 加载数据库列表
  const loadDatabases = async () => {
    if (!connection) return

    setLoading(true)
    try {
      const response = await getDatabases(connection.id)
      if (response.success) {
        setDatabases(response.data)
        if (response.data.length > 0) {
          const defaultDb = connection.database_name || response.data[0]
          setSelectedDatabase(defaultDb)
          await loadTables(defaultDb)
        }
      }
    } catch (error) {
      console.error('Failed to load databases:', error)
      // 使用模拟数据
      const mockDatabases = ['analytics', 'warehouse', 'logs', 'metrics']
      setDatabases(mockDatabases)
      setSelectedDatabase(mockDatabases[0])
      await loadMockTables(mockDatabases[0])
    } finally {
      setLoading(false)
    }
  }

  // 加载表列表
  const loadTables = async (database: string) => {
    if (!connection) return

    try {
      const response = await getTables(connection.id, database)
      if (response.success) {
        buildTreeData(database, response.data)
      }
    } catch (error) {
      console.error('Failed to load tables:', error)
      await loadMockTables(database)
    }
  }

  // 加载模拟表数据
  const loadMockTables = async (database: string) => {
    const mockTables = [
      'users', 'orders', 'products', 'categories', 
      'user_sessions', 'audit_logs', 'system_config'
    ]
    buildTreeData(database, mockTables)
  }

  // 构建树形数据
  const buildTreeData = (database: string, tables: string[]) => {
    const treeNodes: SchemaTreeNode[] = [{
      key: database,
      title: (
        <Space>
          <DatabaseOutlined style={{ color: '#1890ff' }} />
          <span>{database}</span>
          <Tag size="small">{tables.length} 表</Tag>
        </Space>
      ),
      type: 'database',
      database,
      children: tables.map(table => ({
        key: `${database}.${table}`,
        title: (
          <Space>
            <TableOutlined style={{ color: '#52c41a' }} />
            <span>{table}</span>
          </Space>
        ),
        type: 'table',
        database,
        table,
        isLeaf: true,
      })),
    }]

    setTreeData(treeNodes)
    setExpandedKeys([database])
  }

  // 加载表结构
  const loadTableSchema = async (database: string, table: string) => {
    if (!connection) return

    setLoading(true)
    try {
      const response = await getTableSchema(connection.id, database, table)
      if (response.success) {
        const columns = response.data.columns.map(col => ({
          ...col,
          isPrimaryKey: Math.random() > 0.8, // 模拟主键
          isIndex: Math.random() > 0.6, // 模拟索引
        }))
        setTableColumns(columns)
      }
    } catch (error) {
      console.error('Failed to load table schema:', error)
      // 使用模拟数据
      const mockColumns: TableColumn[] = [
        {
          name: 'id',
          type: 'BIGINT',
          nullable: false,
          comment: '主键ID',
          isPrimaryKey: true,
          isIndex: true,
        },
        {
          name: 'name',
          type: 'VARCHAR(255)',
          nullable: false,
          comment: '名称',
          isIndex: true,
        },
        {
          name: 'email',
          type: 'VARCHAR(255)',
          nullable: true,
          comment: '邮箱地址',
          isIndex: true,
        },
        {
          name: 'status',
          type: 'TINYINT',
          nullable: false,
          default: '1',
          comment: '状态：1-正常，0-禁用',
        },
        {
          name: 'created_at',
          type: 'DATETIME',
          nullable: false,
          default: 'CURRENT_TIMESTAMP',
          comment: '创建时间',
        },
        {
          name: 'updated_at',
          type: 'DATETIME',
          nullable: false,
          default: 'CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
          comment: '更新时间',
        },
      ]
      setTableColumns(mockColumns)
    } finally {
      setLoading(false)
    }
  }

  // 处理数据库切换
  const handleDatabaseChange = async (database: string) => {
    setSelectedDatabase(database)
    setSelectedTable(undefined)
    setTableColumns([])
    await loadTables(database)
  }

  // 处理表选择
  const handleTableSelect = (selectedKeys: React.Key[], info: any) => {
    const node = info.node as SchemaTreeNode
    if (node.type === 'table' && node.database && node.table) {
      setSelectedTable(node.table)
      loadTableSchema(node.database, node.table)
    }
  }

  // 复制表结构DDL
  const handleCopyDDL = async () => {
    if (!selectedTable || !selectedDatabase) return

    const ddl = generateDDL(selectedDatabase, selectedTable, tableColumns)
    const success = await copyToClipboard(ddl)
    if (success) {
      message.success('DDL已复制到剪贴板')
    }
  }

  // 生成DDL语句
  const generateDDL = (database: string, table: string, columns: TableColumn[]): string => {
    const columnDefs = columns.map(col => {
      let def = `  \`${col.name}\` ${col.type}`
      if (!col.nullable) def += ' NOT NULL'
      if (col.default) def += ` DEFAULT ${col.default}`
      if (col.comment) def += ` COMMENT '${col.comment}'`
      return def
    }).join(',\n')

    const primaryKeys = columns.filter(col => col.isPrimaryKey).map(col => col.name)
    const primaryKeyDef = primaryKeys.length > 0 
      ? `,\n  PRIMARY KEY (${primaryKeys.map(key => `\`${key}\``).join(', ')})`
      : ''

    return `CREATE TABLE \`${database}\`.\`${table}\` (
${columnDefs}${primaryKeyDef}
) ENGINE=OLAP
COMMENT '${table} 表';`
  }

  // 表格列定义
  const columns: ColumnsType<TableColumn> = [
    {
      title: '字段名',
      dataIndex: 'name',
      key: 'name',
      width: 150,
      render: (name: string, record: TableColumn) => (
        <Space>
          <ColumnHeightOutlined style={{ color: '#1890ff' }} />
          <Text strong={record.isPrimaryKey}>{name}</Text>
          {record.isPrimaryKey && (
            <Tooltip title="主键">
              <KeyOutlined style={{ color: '#faad14' }} />
            </Tooltip>
          )}
        </Space>
      ),
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      render: (type: string) => <Text code>{type}</Text>,
    },
    {
      title: '允许空值',
      dataIndex: 'nullable',
      key: 'nullable',
      width: 100,
      render: (nullable: boolean) => (
        <Tag color={nullable ? 'orange' : 'green'}>
          {nullable ? '是' : '否'}
        </Tag>
      ),
    },
    {
      title: '默认值',
      dataIndex: 'default',
      key: 'default',
      width: 120,
      render: (defaultValue?: string) => (
        defaultValue ? <Text code>{defaultValue}</Text> : <Text type="secondary">-</Text>
      ),
    },
    {
      title: '索引',
      key: 'index',
      width: 80,
      render: (_, record: TableColumn) => (
        record.isIndex ? (
          <Tag color="blue" size="small">索引</Tag>
        ) : (
          <Text type="secondary">-</Text>
        )
      ),
    },
    {
      title: '注释',
      dataIndex: 'comment',
      key: 'comment',
      ellipsis: true,
      render: (comment?: string) => (
        comment ? (
          <Tooltip title={comment}>
            <Text>{comment}</Text>
          </Tooltip>
        ) : (
          <Text type="secondary">-</Text>
        )
      ),
    },
  ]

  // 过滤树数据
  const filterTreeData = (data: SchemaTreeNode[], keyword: string): SchemaTreeNode[] => {
    if (!keyword) return data

    return data.map(node => {
      const children = node.children ? filterTreeData(node.children, keyword) : undefined
      const titleText = typeof node.title === 'string' ? node.title : node.table || node.database || ''
      
      if (titleText.toLowerCase().includes(keyword.toLowerCase()) || (children && children.length > 0)) {
        return { ...node, children }
      }
      
      return null
    }).filter(Boolean) as SchemaTreeNode[]
  }

  useEffect(() => {
    if (visible && connection) {
      loadDatabases()
    }
  }, [visible, connection])

  if (!connection) return null

  const filteredTreeData = filterTreeData(treeData, searchKeyword)

  return (
    <Modal
      title={
        <Space>
          <DatabaseOutlined />
          <span>数据库结构 - {connection.name}</span>
        </Space>
      }
      open={visible}
      onCancel={onClose}
      footer={null}
      width={1200}
      style={{ top: 20 }}
    >
      <Row gutter={[16, 16]}>
        {/* 左侧：数据库和表树 */}
        <Col xs={24} lg={8}>
          <Card
            title="数据库结构"
            size="small"
            extra={
              <Button
                type="text"
                size="small"
                icon={<ReloadOutlined />}
                onClick={loadDatabases}
                loading={loading}
              />
            }
          >
            <Space direction="vertical" style={{ width: '100%' }}>
              <Select
                style={{ width: '100%' }}
                placeholder="选择数据库"
                value={selectedDatabase}
                onChange={handleDatabaseChange}
                loading={loading}
              >
                {databases.map(db => (
                  <Option key={db} value={db}>
                    <Space>
                      <DatabaseOutlined />
                      {db}
                    </Space>
                  </Option>
                ))}
              </Select>

              <Search
                placeholder="搜索表名"
                value={searchKeyword}
                onChange={(e) => setSearchKeyword(e.target.value)}
                style={{ width: '100%' }}
              />

              <div style={{ height: 400, overflow: 'auto' }}>
                {filteredTreeData.length > 0 ? (
                  <Tree
                    treeData={filteredTreeData}
                    onSelect={handleTableSelect}
                    expandedKeys={expandedKeys}
                    onExpand={setExpandedKeys}
                    showIcon
                  />
                ) : (
                  <Empty
                    image={Empty.PRESENTED_IMAGE_SIMPLE}
                    description="暂无数据"
                  />
                )}
              </div>
            </Space>
          </Card>
        </Col>

        {/* 右侧：表结构详情 */}
        <Col xs={24} lg={16}>
          <Card
            title={
              selectedTable ? (
                <Space>
                  <TableOutlined />
                  <span>{selectedDatabase}.{selectedTable}</span>
                </Space>
              ) : (
                '表结构详情'
              )
            }
            size="small"
            extra={
              selectedTable && (
                <Space>
                  <Button
                    type="text"
                    size="small"
                    icon={<CopyOutlined />}
                    onClick={handleCopyDDL}
                  >
                    复制DDL
                  </Button>
                  <Button
                    type="text"
                    size="small"
                    icon={<InfoCircleOutlined />}
                    onClick={() => message.info('表结构信息已加载')}
                  >
                    详情
                  </Button>
                </Space>
              )
            }
          >
            {loading ? (
              <div style={{ textAlign: 'center', padding: '40px 0' }}>
                <Spin size="large" />
              </div>
            ) : selectedTable && tableColumns.length > 0 ? (
              <div>
                <div style={{ marginBottom: 16 }}>
                  <Space>
                    <Text strong>字段数量：</Text>
                    <Tag>{tableColumns.length}</Tag>
                    <Text strong>主键：</Text>
                    <Tag color="gold">
                      {tableColumns.filter(col => col.isPrimaryKey).length}
                    </Tag>
                    <Text strong>索引：</Text>
                    <Tag color="blue">
                      {tableColumns.filter(col => col.isIndex).length}
                    </Tag>
                  </Space>
                </div>

                <Table
                  columns={columns}
                  dataSource={tableColumns}
                  rowKey="name"
                  size="small"
                  pagination={false}
                  scroll={{ y: 350 }}
                />
              </div>
            ) : (
              <Empty
                image={Empty.PRESENTED_IMAGE_SIMPLE}
                description={selectedTable ? '暂无字段信息' : '请选择一个表查看结构'}
              />
            )}
          </Card>
        </Col>
      </Row>
    </Modal>
  )
}

export default DatabaseSchema